<?php
declare (strict_types=1);

namespace app\api\controller;

use app\BaseController;
use app\lib\exception\BaseException;
use app\middleware\api\Auth;
use app\model\CouponUsers;
use app\model\RecordIntegral;
use app\model\Users;
use app\validate\api\CheckId;
use think\facade\Db;

class Coupon extends BaseController
{

    protected $middleware = [
        Auth::class=>['except'=>'index']
    ];

    /**
     * 所有优惠券
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index($limit=10)
    {
        return $this->success(\app\model\Coupon::order('id','desc')->paginate($limit));
    }

    /**
     * 我的优惠券
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function myCoupon()
    {
//        $user = request()->userid;
//        return $this->success(CouponUsers::with('coupon')->where('users_id', $user)->whereExists('coupon')->select());

        $userId = request()->userid;

        $coupons = CouponUsers::with('coupon')
            ->where('users_id', $userId)
            ->whereExists(function ($query) {
                $query->table('coupon')->whereColumn('coupon.id', 'coupon_users.coupon_id');
            })
            ->select();

        return $this->success($coupons);
    }

    /**
     * 兌換優惠券
     * @param $id
     * @return \think\response\Json
     * @throws BaseException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function exchange()
    {




        (new CheckId())->goCheck();
        $user = request()->userid;
        $id = request()->param('id');
        $integrate = Users::where('id', $user)->value('integral_ing');
        $coupon = \app\model\Coupon::find($id);

        if ($coupon->end_time < time()) {
            throw new BaseException(['msg' => '優惠券活動已結束', 'errorCode' => 400]);
        }

        $is_coupon = CouponUsers::where('users_id', $user)->where('coupon_id', $id)->find();
        if (!empty($is_coupon)) {
            throw new BaseException(['msg' => '該優惠券已兌換！']);
        }

// 當優惠券所需積分大於 0 時檢查積分
        if ($coupon->integral > 0) {
            if (empty($integrate) || $integrate < $coupon->integral) {
                throw new BaseException(['msg' => '所需積分不足，兌換失敗！']);
            }
        }

// 執行兌換操作
        CouponUsers::create(['users_id' => $user, 'coupon_id' => $id]);

        if ($coupon->integral > 0) {
            Users::where('id', $user)->dec('integral_ing', $coupon->integral)->update();
            RecordIntegral::record($user, $coupon->integral, RecordIntegral::TYPE_C, RecordIntegral::STATUS_DEC);
        }

        return $this->success();

    }


}
